
package com.william.killian.trivia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

import com.william.killian.trivia.model.Quiz;
import com.william.killian.trivia.util.Util;

public class QuizLoader extends Activity
{

    @Override
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        Util.SetAppPath (getFilesDir ());
        String file = System.currentTimeMillis () + ".xml";
        final File f = new File (Util.getApplicationDirectory (), file);
        try
        {
            String path = getIntent ().getDataString ();
            boolean useURL = path.startsWith ("http");
            
            File existing = null;
            Quiz q = null;
            
            if (useURL)
            {
                q = Quiz.Load (path);
            }
            else
            {
                existing = new File (path);
                q = Quiz.Load (existing);
            }
            if (q == null)
            {
                new AlertDialog.Builder (QuizLoader.this).setTitle (R.string.error).setMessage (R.string.text_load_error).setPositiveButton ("Close", new Closer ()).show ();
            }
            else
            {
                if (!useURL)
                {
                    InputStream in = new FileInputStream (existing);
                    OutputStream out = new FileOutputStream (f);
                    byte[] buf = new byte [1024];
                    int len;
                    while ((len = in.read (buf)) > 0)
                    {
                        out.write (buf, 0, len);
                    }
                    in.close ();
                    out.close ();
                }
                new AlertDialog.Builder (QuizLoader.this).setTitle (R.string.title_import).setMessage (R.string.text_import).setNeutralButton (R.string.close, new Closer ()).show ();
            }
        }
        catch (Exception e)
        {
            new AlertDialog.Builder (QuizLoader.this).setTitle (R.string.error).setMessage (R.string.text_copy_error).setPositiveButton ("Close", new Closer ()).show ();
        }
    }

    private class Closer implements OnClickListener
    {

        public void onClick (DialogInterface dialog, int which)
        {
            QuizLoader.this.finish ();
        }

    }
}
